<template>
  <view class="overview-page" style="padding-bottom: 100rpx;">
    <!-- 顶部：搜索 -->
    <view class="search-bar">
      <input class="search-input" v-model="keyword" placeholder="搜索客户名称" @confirm="onSearch" />
    </view>

    <!-- 客户分组列表 -->
    <scroll-view scroll-y class="customer-list" v-if="customers.length">
      <view class="customer-item" v-for="item in customers" :key="item.customerName">
        <view class="customer-header" @click="toggleExpand(item.customerName, item)">
          <view class="header-left">
            <view class="customer-info">
              <text class="customer-name">{{ item.customerName }}</text>
              <view class="project-count-badge">
                <text class="project-count-text">{{ item.projects.length || 0 }}个项目</text>
              </view>
            </view>
          </view>
          <view class="header-right">
            <view class="amounts-container">
              <view class="amount-row">
                <text class="sum-label">总合同：</text>
                <text class="sum-value">¥{{ formatAmount(item.totalContractAmount) }}</text>
              </view>
              <view class="amount-row">
                <text class="sum-label">总结算：</text>
                <text class="sum-value">¥{{ formatAmount(item.totalSettlementAmount) }}</text>
              </view>
              <view class="amount-row">
                <text class="sum-label">总实收：</text>
                <text class="sum-value">¥{{ formatAmount(item.totalReceivedAmount) }}</text>
              </view>
              <view class="amount-row">
                <text class="sum-label">总未收：</text>
                <text class="sum-value highlight">¥{{ formatAmount(item.totalUnpaidAmount) }}</text>
              </view>
            </view>
            <text class="expand-icon">{{ expanded[item.customerName] ? '▲' : '▼' }}</text>
          </view>
        </view>

        <!-- 项目明细 -->
       <view v-if="expanded[customer.customerName]" class="project-list">
          <view class="project-item" v-for="proj in customer.projects" :key="proj.id" @click="goEditProject(proj)">
            <view class="proj-main">
              <text class="proj-name">{{ proj.project_name || proj.projectName }}</text>
              <text class="contract">合同：¥{{ formatAmount(proj._contractAmount) }}</text>
            </view>
            <view class="proj-amounts">
              <text class="received">已收：¥{{ formatAmount(proj._receivedAmount) }}</text>
              <text class="settlement">结算：¥{{ formatAmount(proj._settlementAmount) }}</text>
              <text class="unpaid">未收：¥{{ formatAmount(proj._unpaidAmount) }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="empty" v-else>
      <image src="/static/empty.png" class="empty-img" />
      <text class="empty-text">暂无客户数据</text>
    </view>

    <custom-tabbar :current="tabIndex" :tabList="tabList" />
  </view>
  
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/CustomTabbar.vue'
import { getTabListByRole } from '@/utils/tabberList.js'
import { getProjectStatusList } from '@/api/sale/customer.js'

export default {
  components: { CustomTabbar },
  data() {
    return {
      tabList: [],
      tabIndex: 0,
      keyword: '',
      expanded: {},
      customers: [], // [{ customerName, projects: [], totalContractAmount, totalUnpaidAmount }]
	  searchTxt: '',
	  customer: {}
    }
  },
  computed: {
    filteredCustomers() {
      if (!this.keyword) return this.customers
      const kw = this.keyword.toLowerCase()
      return this.customers.filter(c => (c.customerName || '').toLowerCase().includes(kw))
    }
  },
  onShow() {
    const role = uni.getStorageSync('user-role')
    this.tabList = getTabListByRole(role)
    let currentPath = ''
    const pages = getCurrentPages()
    if (pages.length) {
      currentPath = pages[pages.length - 1].route || pages[pages.length - 1].__route__ || ''
    }
    this.tabIndex = this.tabList.findIndex(item => item.pagePath === currentPath)

    this.loadData()
  },
  methods: {
    onSearch(val) {
		this.searchTxt = val.detail.value;
		this.loadData();
	},
    toggleExpand(name, obj) {
      this.$set(this.expanded, name, !this.expanded[name])
	  this.customer = obj;
    },
    formatAmount(val) {
      const n = Number(val || 0)
      return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    // 统一提取金额字段
    normalizeAmounts(item) {
      const contract = Number(
        item.contract_amount ?? item.settlement_amount ?? item.contractAmount ?? 0
      )
      const settlement = Number(
        item.settlement_amount ?? item.settlementAmount ?? 0
      )
      const received = Number(
        item.received_amount ?? item.receivedAmount ?? 0
      )
      const unpaid = Math.max(settlement - received, 0) // 基于结算金额计算未收金额
      return { contract, settlement, received, unpaid }
    },
    // 拉取并分组
    async loadData() {
      try {
        // 可按需添加筛选条件，例如只拉取进行中的项目
        const res = await getProjectStatusList({ searchTxt: this.searchTxt })
        // 兼容不同响应结构
        const list = res?.data || []
        this.customers = list
      } catch (error) {
        console.error('加载客户数据失败', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    // 跳转到财务收款计划详情
    goEditProject(item) {
      const id = item.id
      const data = encodeURIComponent(JSON.stringify(item))
      uni.navigateTo({ url: `/pages/finance/detail?id=${id}&data=${data}` })
    }
  }
}
</script>

<style lang="scss" scoped>
.overview-page {
  min-height: 100vh;
  background: #f5f6fa;
  box-sizing: border-box;
  padding: 20rpx 20rpx 0;
}

.search-bar {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin: 20rpx 0;
}

.search-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: #fafafa;
}

.customer-list {
  height: calc(100vh - 260rpx);
}

.customer-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.customer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
}

.header-left {
  display: flex;
  align-items: baseline;
  gap: 12rpx;
}

.customer-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.customer-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.header-right {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
}

.amounts-container {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  min-width: 200rpx;
}

.amount-row {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  justify-content: space-between;
}

.sum-label {
  font-size: 22rpx;
  color: #666;
  white-space: nowrap;
}

.sum-value {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
}

.sum-value.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.expand-icon {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.project-list {
  padding: 0 20rpx 20rpx;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 16rpx;
  border-radius: 12rpx;
  background: #fafafa;
  margin-top: 12rpx;
}

.proj-main {
  display: flex;
  flex-direction: column;
}

.proj-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.contract {
  font-size: 24rpx;
  color: #999;
}

.proj-amounts {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  align-items: flex-end;
}

.received {
  font-size: 24rpx;
  color: #409eff;
}

.settlement {
  font-size: 24rpx;
  color: #666;
}

.unpaid {
  font-size: 24rpx;
  color: #e6a23c;
}

.project-count-badge {
  background: #f0f8ff;
  border: 1rpx solid #409eff;
  border-radius: 12rpx;
  padding: 6rpx 12rpx;
  align-self: flex-start;
}

.project-count-text {
  font-size: 22rpx;
  color: #409eff;
  font-weight: 500;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: calc(100vh - 300rpx);
  padding: 100rpx 0;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>


